<template>
  <div class="app-container">
<br>
<br>
    <div class="header">
      <div style="display: flex;flex-direction: column;justify-content: end;width: 50%;">
        <el-form :model="query" ref="query" label-width="80px" style="width: 100%;">
          <el-row :gutter=10>
            <el-col :span=8>
              <el-form-item label="姓名/编号" prop="name" >
                  <el-input v-model="query.name" placeholder="请输入姓名/编号"/>
              </el-form-item>
            </el-col>
            <el-col :span=12>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="search" >搜索</el-button>
                <el-button @click="resetForm('query')">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <el-card class="box-card" v-for="report in reports" :key="report.jobOfficeId"  >
        <div slot="header" class="clearfix">
          <span>{{ report.jobOfficeName }}</span>
        </div>
        <div class="text item">
          {{'候诊人数: ' + report.waitingCount }}
        </div>
        <div class="text item">
          {{'就诊人数: ' + report.doingCount }}
        </div>
      </el-card>
    </div>
    <br>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      :row-class-name="tableRowClassName"
    > 
      <el-table-column align="center" label="序号" width="50">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="会员编号" width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.patientCode }}
        </template>
      </el-table-column>
      <el-table-column label="会员姓名" width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.patientName }}
        </template>
      </el-table-column>
      <el-table-column label="会员等级" width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.vipLevel }}
        </template>
      </el-table-column>
      <el-table-column label="就诊方式" width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.typeName }}
        </template>
      </el-table-column>
      <el-table-column label="就诊医生" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.doctorName }}
        </template>
      </el-table-column>
      <el-table-column label="就诊科室" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.jobOfficeName }}
        </template>
      </el-table-column>
      <el-table-column label="就诊诊室" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.workAddressName }}
        </template>
      </el-table-column>
      <el-table-column label="就诊类型" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.visitType }}
        </template>
      </el-table-column>
      <el-table-column label="诊前静息剩余时间" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.remainderTime }}
        </template>
      </el-table-column>
      <el-table-column label="挂号后时长" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.durationTime }}
        </template>
      </el-table-column>
      <el-table-column label="挂号费(元)" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.registerPrice }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="150" align="center">
        <template slot-scope="scope">
          <el-tag >{{ scope.row.status | statusFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="操作" align="center" width="400" >
        <template slot-scope="scope">
          <el-dropdown size="medium" trigger="click" @command="optionPatient" >
            <el-button type="primary">
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>

            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="composeValue(scope.row, 1)" >会员基础信息查询</el-dropdown-item>
              <el-dropdown-item :command="composeValue(scope.row, 3)" divided>诊中·实验室检查开立</el-dropdown-item>
              <el-dropdown-item :command="composeValue(scope.row, 4)" >诊中·检查开立</el-dropdown-item>
              <el-dropdown-item :command="composeValue(scope.row, 2)" >诊中·信息采集</el-dropdown-item>
              <el-dropdown-item :command="composeValue(scope.row, 9)" >诊中·诊断开具</el-dropdown-item>
              <el-dropdown-item :command="composeValue(scope.row, 10)" >诊中·处方开具</el-dropdown-item>
              <el-dropdown-item :command="composeValue(scope.row, 11)" >诊中·预案填写</el-dropdown-item>
              <el-dropdown-item :command="composeValue(scope.row, 6)" divided>会员就诊记录查询</el-dropdown-item>
              <el-dropdown-item :command="composeValue(scope.row, 7)" divided>会员缴费/卡/券记录查询</el-dropdown-item>
              <el-dropdown-item :command="composeValue(scope.row, 8)" divided>会员租借药盒记录查询</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- <el-button type="warning"  @click="update(scope.row)" size="small" v-if="scope.row.isDetail === 0">采集信息</el-button>
          <el-button type="warning"  @click="visit(scope.row)" size="small" v-if="scope.row.isDetail != 0 && scope.row.status === 0 ">就诊</el-button>
          <el-button type="primary"  @click="getInfo(scope.row)" size="small">详情</el-button>
          <el-button type="success"  @click="update(scope.row)" size="small">修改</el-button>
          <el-button type="danger" @click="discontinue(scope.row)" size="small">中止</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="->, total, prev, pager, next"
      :total="this.total"
      :current-page="currentPage"
      :page-size="pageSize"
      @current-change="clickCurPage"
      >
    </el-pagination>
  <el-dialog title="候诊详情" :visible.sync="infoVisible" width="1200px">
      <h2>候诊信息</h2>
      <el-form ref="info" :model="info" label-width="120px">
        <el-row :gutter="10">
          <el-col :span=8 >
            <el-form-item label="编号">
              <el-input v-model="info.patientCode" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span=8 >
            <el-form-item label="姓名">
              <el-input v-model="info.patientName" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span=8 >
            <el-form-item label="性别">
              <el-input v-model="info.patientSex" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row  :gutter="10">
          <el-col :span=8 >
            <el-form-item label="科室">
              <el-select v-model="form.jobOfficeId" placeholder="请选择" :disabled="true">
                <el-option
                  v-for="item in jobOfficeEnum"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  @click.native="selectJobOffice(item)"
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span=8 >
            <el-form-item label="模板">
              <el-select v-model="form.templateId" placeholder="请选择" :disabled="true">
                <el-option
                  v-for="item in templateEnum"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div style="width:100%;border: 2px solid #E4E7ED;padding: 10px;">
          <div v-for="(template, index) in info.templateDetailList" :key="index">
            <el-form-item :label="template.column" label-width="150px" v-if="template.type === 1" :rules="[{required:template.required, message:'请输入'+template.column, trigger:'blur'}]" >
              <el-input v-model="template.value" :disabled="true"/>
            </el-form-item>
            <el-form-item :label="template.column" label-width="150px" v-if="template.type === 2" :rules="[{required:template.required, message:'请选择'+template.column, trigger:'blur'}]">
              <el-select v-model="template.value" placeholder="请选择" :disabled="true">
                <el-option
                  v-for="item in template.typeValues"
                  :key="item"
                  :label="item"
                  :value="item"
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
      </el-form>
  </el-dialog>

  <el-dialog :title="dialogTitle" :visible.sync="formVisible" :closeOnClickModal="false" width="1200px">
      <h2>候诊信息</h2>
      <el-form ref="form" :model="form" label-width="120px" :rules="formRules">
        <el-row :gutter="10">
          <el-col :span=8 >
            <el-form-item label="编号">
              <el-input v-model="form.patientCode" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span=8 >
            <el-form-item label="姓名">
              <el-input v-model="form.patientName" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span=8 >
            <el-form-item label="性别">
              <el-input v-model="form.patientSex" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row  :gutter="10">
          <el-col :span=8 >
            <el-form-item label="科室">
              <el-select v-model="form.jobOfficeId" placeholder="请选择" >
                <el-option
                  v-for="item in jobOfficeEnum"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  @click.native="selectJobOffice(item)"
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span=8 >
            <el-form-item label="模板">
              <el-select v-model="form.templateId" placeholder="请选择" >
                <el-option
                  v-for="item in templateEnum"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  @click.native="selectTemplate(item)"
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <div style="width:100%;border: 2px solid #E4E7ED;padding: 10px;">
          <div v-for="(template, index) in form.templateDetailList" :key="index">
            <el-form-item :label="template.column" label-width="150px" v-if="template.type === 1" :rules="[{required:template.required, message:'请输入'+template.column, trigger:'blur'}]" >
              <el-input v-model="template.value" />
            </el-form-item>
            <el-form-item :label="template.column" label-width="150px" v-if="template.type === 2" :rules="[{required:template.required, message:'请选择'+template.column, trigger:'blur'}]">
              <el-select v-model="template.value" placeholder="请选择" >
                <el-option
                  v-for="item in template.typeValues"
                  :key="item"
                  :label="item"
                  :value="item"
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirm">确 定</el-button>
          <div style="width:200px;display: inline-block;"> </div>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
      
  </el-dialog>
  </div>
</template>

<script>

import { getList, addOrUpdate, guidanceWaitingNumber} from '@/api/guidance'
import { getList as getJobOfficeList} from '@/api/jobOffice'
import { getList as getTemplate} from '@/api/guidanceTemplate'



export default {
  filters: {
    statusFilter(status) {
      const statusMap = ['候诊', '就诊中', '已完成', '中止']
      return statusMap[status]
    }
  },
  data() {
    const validateName = (rule, value, callback) => {
      if (!value) callback(new Error('请输入姓名')) 
      else callback()
    }
    const validatePhone = (rule, value, callback) => {
      if (!value) callback(new Error('请输入电话')) 
      else callback()
    }
    const validateIdCard = (rule, value, callback) => {
      if (!value) callback(new Error('请输入身份证号')) 
      else callback()
    }
    const validateSex = (rule, value, callback) => {
      if (!value) callback(new Error('请选择性别')) 
      else callback()
    }
    const validateBirthday = (rule, value, callback) => {
      if (!value) callback(new Error('请选择出生日期')) 
      else callback()
    }
    const validateBirthdayType = (rule, value, callback) => {
      if (!value) callback(new Error('请选择类型')) 
      else callback()
    }
    const validateSource = (rule, value, callback) => {
      if (!value) callback(new Error('请选择来源')) 
      else callback()
    }
    const validateDistance = (rule, value, callback) => {
      if (!value) callback(new Error('请选择距离(站)')) 
      else callback()
    }
    const validateAddressPre = (rule, value, callback) => {
      var flag = false
      for (const address of this.form.addressList) {
        if(!address.addressPre || address.addressPre.length < 3) flag = true
      }
      if (flag) callback(new Error('地址不能为空')) 
      else callback()
    }
    const validateAddressInfo = (rule, value, callback) => {
      var flag = false
      for (const address of this.form.addressList) {
        if(!address.addressInfo || address.addressInfo === '') flag = true
      }
      if (flag) callback(new Error('地址不能为空')) 
      else callback()
    }
    return {
      list: null,
      listLoading: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      curIndex: -1,
      infoVisible: false,
      formVisible: false,
      info: {},
      form: {},
      dialogTitle: '添加',
      birthdayTypeEnum:[{id: 1, name: '公历'}, {id: 2, name: '农历'}],
      sourceEnum: [],
      userEnum: [],
      sexEnum: ["男", "女"],
      jobOfficeEnum: [],
      formRules: {
        name: [{ required: true, trigger: 'blur', validator: validateName }],
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        idCard: [{ required: true, trigger: 'blur', validator: validateIdCard }],
        sex: [{ required: true, trigger: 'blur', validator: validateSex }],
        birthday: [{ required: true, trigger: 'blur', validator: validateBirthday }],
        birthdayType: [{ required: true, trigger: 'blur', validator: validateBirthdayType }],
        source: [{ required: true, trigger: 'blur', validator: validateSource }],
        distance: [{ required: true, trigger: 'blur', validator: validateDistance }],
        addressPre: [{ required: true, trigger: 'blur', validator: validateAddressPre }],
        addressInfo: [{ required: true, trigger: 'blur', validator: validateAddressInfo }],
      },
      query: {},
      intervalId: null,
      templateEnum: [],
      reports: [],
    }
  },
  created() {
    this.fetchData()
    this.startInterval();
  },
  beforeDestroy() {
    this.stopInterval();
  },
  directives: {
    required: {
      inserted(el, binding) {
        el.addEventListener('blur', () => {
          if (el.value.trim() === '') {
            alert(binding.value);
          }
        });
      }
    }
  },
  methods: {
    fetchData() {
      this.listLoading = true
      var loginInfo = this.$store.getters.userInfo.loginInfo
      var deptId = loginInfo.loginDept.deptId
      // var workAddressId = loginInfo.loginWorkAddress.id
      var jobOfficeId = loginInfo.loginJobOffice?loginInfo.loginJobOffice.jobOfficeId:undefined
      console.log("loginInfo", loginInfo)
      getList({currentPage: this.currentPage, pageSize: this.pageSize, deptId: deptId, jobOfficeId: jobOfficeId}).then(res=>{
        console.log(res.data)
        this.list = res.data.records
        this.listLoading = false
      }).catch(err=>{
        console.log("err")
        console.log(err)
        this.listLoading = false
      })
      guidanceWaitingNumber({deptId: deptId, workAddressId: undefined, jobOfficeId: jobOfficeId}).then(res=> {
        this.reports = res.data
      })
    },
    clickCurPage(val){
      this.currentPage = val
      this.fetchData()
    },
    getInfo(row) {
      this.info = row
      getJobOfficeList({userId: this.form.doctorId}).then(res=>{
        this.jobOfficeEnum = res.data
        getTemplate({jobOfficeId: row.jobOfficeId}).then(template=>{
          this.templateEnum = template.data
        })
      })
      this.infoVisible = true
    },
    update(row) {
      this.reset()
      this.dialogTitle = '修改候诊'
      this.form = JSON.parse(JSON.stringify(row))
      console.log(this.form)
      getJobOfficeList({userId: this.form.doctorId}).then(res=>{
        this.jobOfficeEnum = res.data
        getTemplate({jobOfficeId: row.jobOfficeId}).then(template=>{
          this.templateEnum = template.data
        })
      })
      this.formVisible = true
    },
    confirm() {
      this.form.templateDetailList.forEach(template=> {
        if(template.required && template.value == undefined) {
          this.$message.error(template.column + '不能为空')
          throw new Error(template.column + '不能为空')
        }
      })
      addOrUpdate(this.form).then(res=>{
        console.log(res)
        this.$message({
          message: '修改成功',
          type: 'success'
        })
        this.formVisible = false
        this.listLoading = false
        this.$tab.refreshPage({path: '/guidance/visitList', name: "VisitList"})
      }).catch(err=>{
        console.log(err)
      })
    },
    cancel() {
      this.formVisible = false
    },
    reset(){
      this.form = {}
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    search() {
      var loginInfo = this.$store.getters.userInfo.loginInfo
      var jobOfficeId = loginInfo.loginJobOffice?loginInfo.loginJobOffice.jobOfficeId:undefined
      getList({currentPage: this.currentPage, pageSize: this.pageSize, name: this.query.name, deptId: loginInfo.loginDept.deptId, workAddressId: loginInfo.loginWorkAddress.id, jobOfficeId: jobOfficeId}).then(res=>{
        this.list = res.data.records
        this.listLoading = false
      }).catch(err=>{
        console.log("err")
        console.log(err)
        this.listLoading = false
      })
    },
    selectJobOffice(jobOffice) {
      this.$set(this.form, 'templateId', '')
      this.$set(this.form, 'templateDetailList', [])
      getTemplate({jobOfficeId: jobOffice.id}).then(res=>{
        console.log(res)
        if(res.data.length == 0) {
          this.$message.error(jobOffice.name + '未设置模板')
          throw new Error()
        }
        this.templateEnum = res.data
      })
    },
    selectTemplate(template) {
      this.form.templateDetailList = template.templateDetailList
    },
    callApi() {
      // 调用接口的逻辑
      console.log('调用接口');
      // 假设你有一个fetchData方法来获取数据
      var loginInfo = this.$store.getters.userInfo.loginInfo
      var jobOfficeId = loginInfo.loginJobOffice?loginInfo.loginJobOffice.jobOfficeId:undefined
      getList({currentPage: this.currentPage, pageSize: this.pageSize, deptId: loginInfo.loginDept.deptId, workAddressId: loginInfo.loginWorkAddress.id, jobOfficeId: jobOfficeId}).then(res=>{
        console.log(res.data)
        this.list = res.data.records
      })
    },
    startInterval() {
      this.intervalId = setInterval(this.callApi, 1000 * 60);
    },
    stopInterval() {
      if (this.intervalId) {
        clearInterval(this.intervalId);
      }
    },
    tableRowClassName({row, rowIndex}) {
      if (row.status === 0 && row.remainderTime === 0) {
        return 'warning-row';
      } else if (row.status != 0) {
        return 'done-row';
      }
      return '';
    },
    discontinue(row) {
      console.log(row)
      this.$confirm('确定中止该候诊?', '中止', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.status = 3
        addOrUpdate(row).then(res=>{
          console.log(res)
          this.$message({
            message: '中止成功',
            type: 'success'
          })
          this.formVisible = false
          this.listLoading = false
          this.$tab.refreshPage({path: '/guidance/visitList', name: "VisitList"})
        }).catch(err=>{
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });          
      });
    },
    visit(row) {
      this.$router.push({name: "VisitPage", params: row});
    },
    composeValue(row, optType) {
      return {
        row,
        optType
      }
    },
    optionPatient(value) {
      if(value.optType == 1) {
        this.getInfo(value.row)
      } else if (value.optType == 2) {
        this.update(value.row)
      } else if (value.optType == 9) {
        this.visit(value.row)
      } else if (value.optType == 10) {
        this.visit(value.row)
      }
    },

  }
}
</script>

<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  .el-table .warning-row {
    background: rgb(255, 0, 0);
  }  
  .el-table .done-row {
    background: #C0C4CC;
  }

  .text {
    font-size: 14px;
  }
  .item {
    margin-bottom: 18px;
  }
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
  .box-card {
    width: 150px;
    margin-right: 10px;
  }

  .header {
    display: flex;
    flex-direction: row;
  }
  
</style>